package simulator.software.scheduling;

import java.util.List;
import java.util.Random;
import java.util.Vector;

import simulator.software.Process;
import simulator.software.ProcessState;

/**
 * Implementation of process scheduling by lottery. The next process to run is
 * chosen from the pool of ready processes at random, with all ready processes
 * having equal likelihood of being chosen.
 * 
 * @author David Joe Wade
 * @author David LaPointe
 * 
 */
public class LotteryScheduler implements Scheduler
{
   private Process lastRan = null;
   Random ticket = new Random();

   public String getDescription()
   {
      return "Lottery Scheduler";
   }

   public Process nextProcess(List<Process> processTable)
   {
      List<Process> readyProcesses = new Vector<Process>();

      for (Process p : processTable)
      {
         if (p.getState() == ProcessState.READY)
         {
            readyProcesses.add(p);
         }
      }

      if (readyProcesses.size() > 0)
      {
         // get a random number between 0 and readyProcesses.size() - 1
         int ticketNumber = (int) Math.round(ticket.nextDouble()
               * (readyProcesses.size() - 1));

         return readyProcesses.get(ticketNumber);
      }
      else
      {
         return null;
      }
   }
}